package database

import (
	"fmt"
	"net/url"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"

	"lux/pkg/config"
	"lux/pkg/model"
)

var DB *gorm.DB

func InitDB() error {
	dsn, err := dbURL()
	if err != nil {
		return fmt.Errorf("get database url failed: %v", err)
	}

	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return fmt.Errorf("connect mysql database failed: %v", err)
	}

	// auto migration
	if err := DB.AutoMigrate(model.Register{}); err != nil {
		return fmt.Errorf("auto migrate table into database failed: %v", err)
	}

	return nil
}

func dbURL() (string, error) {
	dbURL := config.CONF.GetString("database.url")
	u, err := url.Parse(dbURL)
	if err != nil {
		return "", fmt.Errorf("parse database url failed, got an error: %v", err)
	}

	if u.Scheme != "mysql" {
		return "", fmt.Errorf("database url error, only support mysql database")
	}
	u.Scheme = ""

	v := url.Values{}
	v.Set("charset", "utf8mb4")
	v.Set("parseTime", "True")
	v.Set("loc", "Local")
	u.RawQuery = v.Encode()
	return u.String(), nil
}
